package updown.service.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import updown.constant.GeneralConstant;
import updown.dao.TaskInfoDao;
import updown.dao.TaskWrapperDao;
import updown.domain.*;
import updown.service.jar.LocalFileService;
import updown.service.jar.SshService;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Title: ww.kaixin.downupservice.service </p>
 * <p>Description:to-22-6-1: -  </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/12/22
 * @Version: 1.0
 */
@Slf4j
@Service
public class TaskInfoService {

    @Autowired
    private TaskWrapperDao taskWrapperDao;

    @Autowired
    private TaskInfoDao taskInfoDao;

    @Autowired
    private ServerHostService hostService;

    @Autowired
    private SshService sshService;

    @Autowired
    private LocalFileService localFileService;

    /**
     * 保存本次任务信息
     *
     * @param taskWrapper
     */
    public void add(TaskWrapper taskWrapper) {
        dealServerHost(taskWrapper);
        dealJarVersion(taskWrapper);
        List<TaskInfo> taskInfos = taskWrapper.getTaskInfos();
        taskWrapper.setServiceName(taskWrapper.getServiceInfo().getServiceName());
        log.info("保存到数据库 taskWrapper:{}", taskWrapper);
        taskWrapperDao.add(taskWrapper);
        if (!taskInfos.isEmpty()) {
            log.info("保存到数据库 taskInfos:{}", taskInfos);
            for (TaskInfo taskInfo : taskInfos) {
                taskInfo.setTaskId(taskWrapper.getTaskId());
            }
            taskInfoDao.addBatch(taskInfos);
        }
        log.info("保存 task wrapper 信息成功:{},taskInfo:{}", taskWrapper, taskInfos);
    }

    /**
     * 处理 本次服务的 serverhost 信息
     *
     * @param taskWrapper
     */
    private void dealServerHost(TaskWrapper taskWrapper) {
        try {
            // 服务替换
            List<ServerHost> serverHosts = hostService.getServerByServiceName(taskWrapper.getServiceInfo().getServiceName());
            List<String> strings = serverHosts.stream().map(item -> {
                return item.getName() + "-" + item.getHost() + " ";
            }).collect(Collectors.toList());
            taskWrapper.setServerHostInfo(strings.toString());
        } catch (Exception e) {
            log.info("dealServerHost error :{} ", e);
        }
    }

    /**
     * 处理jar包信息
     *
     * @param taskWrapper
     */
    private void dealJarVersion(TaskWrapper taskWrapper) {
        log.info("dealJarVersion(),taskWrapper:{}", taskWrapper);
        try {
            if (GeneralConstant.TASK_WRAPPER_DOWN_UP.equals(taskWrapper.getTaskType()) || GeneralConstant.TASK_WRAPPER_DOWN_UP_SCHEDULE.equals(taskWrapper.getTaskType()) ) {
                //这里服务替换： jar 包上传不需要处理 jar包信息
                long jarSize = sshService.getRandomServerForServiceNameJarSize(taskWrapper);
                List<File> files = localFileService.getLocalJarFileByServiceNameReturnFile(taskWrapper.getServiceName());
                if (files != null && !files.isEmpty()) {
                    for (File file : files) {
                        log.info("dealJarVersion() file:{}", file);
                        if (file.length() == jarSize) {
                            log.info("dealJarVersion() 匹配到了 file:{}", file);
                            taskWrapper.setJarInfo(file.getName());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("dealJarVersion() - error:{}", e);
        }
    }

    /**
     * 查看服务的 所有任务信息
     *
     * @param serviceName
     */
    public List<TaskWrapperMapperBean> getTaskInfoByServiceName(String serviceName) {
        List<TaskWrapperMapperBean> taskWrappers = taskWrapperDao.getByServiceName(serviceName);
        for (TaskWrapperMapperBean taskWrapper : taskWrappers) {
            List<TaskInfoMapperBean> taskInfos = taskInfoDao.getByTaskId(taskWrapper.getTaskId());
            taskWrapper.setTaskInfos(taskInfos);
        }
        return taskWrappers;
    }

    /**
     * 定时任务，查询出 还未执行的任务
     *
     * @param taskId
     * @return
     */
    public TaskWrapper getUnDoneScheduleTaskByTaskId(String taskId) {
        TaskWrapperMapperBean taskWrapperMapperBean = taskWrapperDao.getByTaskId(taskId);
        if (taskWrapperMapperBean == null){
            return null;
        }
        TaskWrapper taskWrapper = taskWrapperMapperBean.convertToTaskWrapper();
        return taskWrapper;
    }

    /**
     * 更新
     * @param taskWrapper
     */
    public void updateTaskWrapper(TaskWrapper taskWrapper) {
        // 删除
        taskWrapperDao.deleteByTaskId(taskWrapper.getTaskId());
        // 重新添加
        add(taskWrapper);
    }

    /**
     * 根据服务查询最近的记录
     * @param serviceName
     * @return
     */
    public TaskWrapperMapperBean getLatestDownUpRecord(String serviceName) {
        TaskWrapperMapperBean taskWrapper = taskWrapperDao.getLatestDownUpRecord(serviceName);
        return taskWrapper;
    }
}
